
<!DOCTYPE html>
<html lang="en">
    <!--百度统计-->
    <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b94bd2699a7baf9292dd9cf571f7fbb9";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
    </script>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="keywords" content="Python,Django,Python教程,Django教程,教程,基础教程,Web开发,运维,自动化,博客,编程,软件,云计算,大数据,爬虫,
    人工智能,机器学习,神经网络" />
    <meta name="description" content="提供Python和Django的原创中文精品教程和博客,分享技术知识,传播新闻视点,提倡开源精神,让更多开发者从中受益。">
    <meta name="author" content="刘江,liujiang,大江东流">
    <title>
    
    django Part 3：视图和模板 - 刘江的django教程
    
</title>
	
	<!-- core CSS -->
    <link href="static/bootstrap.min.css" rel="stylesheet">
    <link href="static/font-awesome.min.css" rel="stylesheet">


    <link href="static/main.css" rel="stylesheet">

    <link href="static/github.css" rel="stylesheet">
    <!--[if lt IE 9]>
    <script src="js/html5shiv.js"></script>
    <script src="js/respond.min.js"></script>
    <![endif]-->       
    <link rel="shortcut icon" href="/static/images/ico/favicon.ico">
    
    <link href="static/course.css" rel="stylesheet">


</head><!--/head-->

<body class="homepage">

    <header id="header" class=" navbar-fixed-top">
        <div class="top-bar">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-6">
                        <div class="top-number">
                            <p><i class="fa fa-feed" aria-hidden="true"></i>&nbsp;
                            <strong style="color: red;">强烈推荐博主精心录制的Python及Django视频教程,<a href="/video/">详情点击</a>!</strong>
                            </p></div>
                    </div>
                    <div class="col-md-offset-3 col-md-3">
                        <span class="pull-left">分享：</span>
                        <!-- JiaThis Button BEGIN社会化分享工具 -->
                        <div class="jiathis_style_24x24">
                            <a class="jiathis_button_qzone"></a>
                            <a class="jiathis_button_tsina"></a>
                            <a class="jiathis_button_tqq"></a>
                            <a class="jiathis_button_weixin"></a>
                            <a class="jiathis_button_renren"></a>
                            <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
                        </div>

                        <!-- JiaThis Button END -->
                    </div>
                </div>
            </div><!--/.container-->
        </div><!--/.top-bar-->

		<nav class="navbar navbar-default navbar-inverse">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#my-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">刘江的博客及教程</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="my-navbar">
      <ul class="nav navbar-nav">
        <li><a href="/news/">新闻</a></li>
        <li><a href="/blog/">博客</a></li>
        <li><a href="/course/python/1">Python教程</a></li>
        <li><a href="2.html">Django教程</a></li>
        <li><a href="/video/">视频教程</a>
        <span class="badge" style="color: red;text-shadow:-1px 0 white,0 1px white,1px 0 white,0 -1px white; float: right;font-size: small;margin-left: -8px;">Hot!</span>
        </li>
      </ul>

      <form id="search-form" method="get" action="/blog/search/" class="navbar-form navbar-left collasped">
        <div class="form-group">
          <input type="text" name="keyword" class="form-control" placeholder="Search" required>
        </div>
        <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
      </form>

      <ul class="nav navbar-nav navbar-right">
          <li>
            
              <!--通过在login后添加next参数，让用户登录后返回先前的页面-->
            <a href="89.html">
            <span class="glyphicon glyphicon-log-in"></span>登录</a></li>
            
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

    </header><!--/header-->


    
    <div class="container-fluid main">
      <div class="row">

        <!-- 左侧目录栏 -->
        <div class="col-md-3">
          <div class="navbar-sider list-group-item">
            目&nbsp;录
            <hr />
            
                
                        
                            
                            <a href="2.html" class="list-group-item"><b>Django教程</b></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="84.html"
                               class="list-group-item"><strong>Django简介</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="85.html"
                               class="list-group-item"><strong>Django环境安装</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="86.html"
                               class="list-group-item"><strong>第一个Django应用</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="87.html"
                               class="list-group-item">Part 1：请求与响应</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="88.html"
                               class="list-group-item">Part 2：模型与管理后台</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="89.html"
                               class="list-group-item active">Part 3：视图和模板</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="90.html"
                               class="list-group-item">Part 4：表单和类视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="91.html"
                               class="list-group-item">Part 5：测试</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="92.html"
                               class="list-group-item">Part 6：静态文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="93.html"
                               class="list-group-item">Part 7：自定义admin站点</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="94.html"
                               class="list-group-item"><strong>第一章：模型层model layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="95.html"
                               class="list-group-item">模型和字段</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="96.html"
                               class="list-group-item">关系类型字段</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="97.html"
                               class="list-group-item">字段的参数</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="98.html"
                               class="list-group-item">多对多中间表详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="99.html"
                               class="list-group-item">模型的元数据Meta</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="100.html"
                               class="list-group-item">模型的继承</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="101.html"
                               class="list-group-item">用包来组织模型</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="129.html"
                               class="list-group-item">查询操作</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="130.html"
                               class="list-group-item">查询集API</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="131.html"
                               class="list-group-item">不返回QuerySets的API</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="132.html"
                               class="list-group-item">字段查询参数及聚合函数</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="133.html"
                               class="list-group-item"><strong>第二章：视图层view layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="182.html"
                               class="list-group-item">Django2.0 URL配置</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="134.html"
                               class="list-group-item">URL路由基础</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="135.html"
                               class="list-group-item">路由转发</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="136.html"
                               class="list-group-item">URL反向解析和命名空间</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="137.html"
                               class="list-group-item">视图函数及快捷方式</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="138.html"
                               class="list-group-item">HttpRequest对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="139.html"
                               class="list-group-item">QueryDict对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="140.html"
                               class="list-group-item">HttpResponse对象</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="141.html"
                               class="list-group-item">文件上传</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="142.html"
                               class="list-group-item">动态生成CSV文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="143.html"
                               class="list-group-item">动态生成PDF文件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="144.html"
                               class="list-group-item"><strong>第三章：模版层Template layer</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="145.html"
                               class="list-group-item">Django模板语言详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="146.html"
                               class="list-group-item">Django内置模板标签</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="147.html"
                               class="list-group-item">Django内置模版过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="148.html"
                               class="list-group-item">特殊的标签和过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="149.html"
                               class="list-group-item">人类可读性</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="150.html"
                               class="list-group-item">自定义模板标签和过滤器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="151.html"
                               class="list-group-item"><strong>第四章：Django表单</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="152.html"
                               class="list-group-item">使用表单</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="153.html"
                               class="list-group-item">Django表单API详解</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="154.html"
                               class="list-group-item">Django表单字段汇总</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="155.html"
                               class="list-group-item">表单的Widgets</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="156.html"
                               class="list-group-item">模型表单ModelForm</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="157.html"
                               class="list-group-item"><strong>第五章：Admin管理后台</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="158.html"
                               class="list-group-item">自定制Admin</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="159.html"
                               class="list-group-item">自定义Admin actions</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="160.html"
                               class="list-group-item">Admin文档生成器</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="162.html"
                               class="list-group-item"><strong>第六章：Django 综合篇</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="163.html"
                               class="list-group-item">配置 Django</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="164.html"
                               class="list-group-item">核心配置项</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="165.html"
                               class="list-group-item">使用MySQL数据库</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="166.html"
                               class="list-group-item">django-admin和manage.py</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="167.html"
                               class="list-group-item">自定义django-admin命令</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="168.html"
                               class="list-group-item">会话session</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="169.html"
                               class="list-group-item">网站地图sitemap</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="170.html"
                               class="list-group-item">信号 signal</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="171.html"
                               class="list-group-item">序列化 serializers</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="172.html"
                               class="list-group-item">消息框架 message</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="173.html"
                               class="list-group-item">分页 Paginator</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="174.html"
                               class="list-group-item">聚合内容 RSS/Atom</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="175.html"
                               class="list-group-item">发送邮件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="176.html"
                               class="list-group-item">Django 日志</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="177.html"
                               class="list-group-item">Django与缓存</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="178.html"
                               class="list-group-item">认证系统 Authentication</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="179.html"
                               class="list-group-item">Django与CSRF 、AJAX</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="180.html"
                               class="list-group-item">Django 国际化和本地化</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="181.html"
                               class="list-group-item">部署 Django</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="102.html"
                               class="list-group-item"><strong>实战一：用户登录与注册系统</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="103.html"
                               class="list-group-item">1. 搭建项目环境</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="104.html"
                               class="list-group-item">2. 设计数据模型</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="105.html"
                               class="list-group-item">3. admin后台</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="106.html"
                               class="list-group-item">4. url路由和视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="107.html"
                               class="list-group-item">5. 前端页面设计</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="108.html"
                               class="list-group-item">6. 登录视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="109.html"
                               class="list-group-item">7. Django表单</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="110.html"
                               class="list-group-item">8. 图片验证码</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="111.html"
                               class="list-group-item">9. session会话</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="112.html"
                               class="list-group-item">10. 注册视图</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="113.html"
                               class="list-group-item">11.使用Django发送邮件</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="114.html"
                               class="list-group-item">12. 邮件注册确认</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="115.html"
                               class="list-group-item">13. 使用Github管理项目</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 2em" href="116.html"
                               class="list-group-item"><strong>实战二：CMDB之资产管理系统</strong></a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="117.html"
                               class="list-group-item">1.项目需求分析</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="118.html"
                               class="list-group-item">2.模型设计</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="119.html"
                               class="list-group-item">3.数据收集客户端</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="120.html"
                               class="list-group-item">4.Windows下收集数据</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="121.html"
                               class="list-group-item">5.Linux下收集数据</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="122.html"
                               class="list-group-item">6.新资产待审批区</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="123.html"
                               class="list-group-item">7.审批新资产</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="124.html"
                               class="list-group-item">8.已上线资产信息更新</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="125.html"
                               class="list-group-item">9.前端框架AdminLTE</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="126.html"
                               class="list-group-item">10.资产总表</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="127.html"
                               class="list-group-item">11.资产详细页面</a>
                            
                        
                
            
                
                        
                            
                            <a style="margin-left: 4em" href="128.html"
                               class="list-group-item">12.dashboard仪表盘</a>
                            
                        
                
            
          </div>
        </div>
        <!-- 左侧目录栏 结束 -->

        <!-- 右侧正文栏 -->
        <div class="col-md-9">
            <!-- 教程正文主体部分 -->
            <div class="row">
                <h1>Part 3：视图和模板</h1>
                <p>阅读:&nbsp;7997</p>
                <hr/>
                <h2 id="_1">一、概述</h2>
<p>一个视图就是一个页面，通常提供特定的功能，使用特定的模板。例如：在一个博客应用中，你可能会看到下列视图：</p>
<ul>
<li>博客主页：显示最新发布的一些内容</li>
<li>每篇博客的详细页面：博客的永久链接</li>
<li>基于年的博客页面：显示指定年内的所有博客文章</li>
<li>基于月的博客页面：显示指定月内的所有博客文章</li>
<li>基于天的博客页面：显示指定日内的所有博客文章</li>
<li>发布评论：处理针对某篇博客发布的评论</li>
</ul>
<p>在我们的投票应用中，我们将建立下面的视图：</p>
<ul>
<li>问卷“index”页：显示最新的一些问卷</li>
<li>问卷“detail”页面：显示一个问卷的详细文本内容，没有调查结果但是有一个投票或调查表单。</li>
<li>问卷“results”页面：显示某个问卷的投票或调查结果。</li>
<li>投票动作页面：处理针对某个问卷的某个选项的投票动作。</li>
</ul>
<p>在Django中，网页和其它的一些内容都是通过视图来处理的。视图其实就是一个简单的Python函数（在基于类的视图中称为方法）。Django通过对比请求的URL地址来选择对应的视图。</p>
<h2 id="_2">二、编写视图</h2>
<p>下面，打开<code>polls/views.py</code>文件，输入下列代码：</p>
<div class="codehilite"><pre><span></span><span class="k">def</span> <span class="nf">detail</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;You&#39;re looking at question </span><span class="si">%s</span><span class="s2">.&quot;</span> <span class="o">%</span> <span class="n">question_id</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">results</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="n">response</span> <span class="o">=</span> <span class="s2">&quot;You&#39;re looking at the results of question </span><span class="si">%s</span><span class="s2">.&quot;</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="n">response</span> <span class="o">%</span> <span class="n">question_id</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">vote</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;You&#39;re voting on question </span><span class="si">%s</span><span class="s2">.&quot;</span> <span class="o">%</span> <span class="n">question_id</span><span class="p">)</span>
</pre></div>


<p>然后，在<code>polls/urls.py</code>文件中加入下面的url模式，将其映射到我们上面新增的视图。</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">views</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="c1"># ex: /polls/</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">index</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;index&#39;</span><span class="p">),</span>
    <span class="c1"># ex: /polls/5/</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;question_id&gt;[0-9]+)/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">detail</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;detail&#39;</span><span class="p">),</span>
    <span class="c1"># ex: /polls/5/results/</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;question_id&gt;[0-9]+)/results/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">results</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;results&#39;</span><span class="p">),</span>
    <span class="c1"># ex: /polls/5/vote/</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;question_id&gt;[0-9]+)/vote/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">vote</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;vote&#39;</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>


<p>现在去浏览器中访问<code>/polls/34/</code>（注意：这里省略了域名。另外，使用了二级路由后，url中都要添加polls部分，参考前面的章节），它将调用<code>detail()</code>函数，然后在页面中显示你在url里提供的ID。访问<code>/polls/34/results/</code>和<code>/polls/34/vote/</code>，将分别显示预定义的伪结果和投票页面。(PS:这里就不贴图了，请大家务必自己动手测试，多实践。）</p>
<p>上面访问的路由过程如下：当有人访问<code>/polls/34/</code>地址时，Django将首先加载<code>mysite.urls</code>模块，因为它是settings文件里设置的根URL配置文件。在该文件里，Django发现了<code>urlpatterns</code>变量，于是在其内按顺序进行匹配。当它匹配上了<code>^polls/</code>，就裁去url中匹配的文本<code>polls/</code>，然后将剩下的文本“34/”，传递给<code>polls.urls</code>进行下一步的处理。在<code>polls.urls</code>中，又匹配到了<code>r’^(?P&lt;question_id&gt;[0-9]+)/$’</code>，最终结果就是调用该模式对应的detail()视图，也就是下面的函数：</p>
<div class="codehilite"><pre><span></span>detail(request=&lt;HttpRequest object&gt;, question_id=&#39;34&#39;)
</pre></div>


<p>函数中的<code>question_id=’34’</code>参数，是由<code>(?P&lt;question_id&gt;[0-9]+)</code>而来。在正则表达式中通过一个双圆括号，Django会捕获它匹配到的值并传递给对应的视图，作为视图的位置参数之一，而<code>?P&lt;question_id&gt;</code>则表示我要给这个捕获的值指定一个特殊的变量名，在视图中可以通过<code>question_id</code>这个变量名随意的引用它，形成一个关键字参数，不用考虑参数的位置。至于<code>[0-9]+</code>则是一个很简单的原生正则表达式，用于匹配一系列连续的数字，它匹配到的值也就是具体要传递的参数值。</p>
<p>所有的URL模式都是正则表达式，Django不限制你在url模式中的书写方式。但是，你真的没必要书写一个如下的较为愚蠢的包含<code>.html</code>的模式，它显然是没必要，不够简练的：</p>
<div class="codehilite"><pre><span></span>url(r&#39;^polls/latest\.html$&#39;, views.index),
</pre></div>


<p>你完全可以用下面的模式代替上面的：</p>
<div class="codehilite"><pre><span></span>url(r&#39;^polls/latest$&#39;, views.index),
</pre></div>


<h2 id="_3">三、编写能实际干点活的视图</h2>
<p>每个视图至少做两件事之一：返回一个包含请求页面的HttpResponse对象或者弹出一个类似Http404的异常。其它的则随你便，你爱干嘛干嘛。</p>
<p>下面是一个新的index()视图，用于替代先前无用的index，它会根据发布日期显示最近的5个投票问卷。</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span>

<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Question</span>

<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">latest_question_list</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;-pub_date&#39;</span><span class="p">)[:</span><span class="mi">5</span><span class="p">]</span>
    <span class="n">output</span> <span class="o">=</span> <span class="s1">&#39;, &#39;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">q</span><span class="o">.</span><span class="n">question_text</span> <span class="k">for</span> <span class="n">q</span> <span class="ow">in</span> <span class="n">latest_question_list</span><span class="p">])</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="n">output</span><span class="p">)</span>

<span class="c1"># 下面是那些没改动过的视图(detail, results, vote)</span>
</pre></div>


<p><strong>这里有个非常重要的问题：在当前视图中的HTML页面是硬编码的。</strong>如果你想改变页面的显示内容，就必须修改这里的Python代码。为了解决这个问题，需要使用Django提供的模板系统，解耦视图和模板之间的硬连接。</p>
<p>首先，在polls目录下创建一个新的<code>templates</code>目录，Django会在它里面查找模板文件。在templates目录中，再创建一个新的子目录名叫<code>polls</code>，进入该子目录，创建一个新的html文件<code>index.html</code>。换句话说，你的模板文件应该是<code>polls/templates/polls/index.html</code>。可以在DJango中直接使用<code>polls/index.html</code>引用该文件。</p>
<h3 id="pycharmtemplates">注意：在Pycharm中，templates文件夹通常已经帮你创建好了！</h3>
<p><strong>模板命名空间：</strong></p>
<p>你也许会想，为什么不把模板文件直接放在polls/templates目录下，而是费劲的再建个子目录polls呢?设想这么个情况，有另外一个app，它也有一个名叫index.html的文件，当Django在搜索模板时，有可能就找到它，然后退出搜索，这就命中了错误的目标，不是我们想要的结果。解决这个问题的最好办法就是在templates目录下再建立一个与app同名的子目录，将自己所属的模板都放到里面，从而达到独立命名空间的作用，不会再出现引用错误。</p>
<p>现在，将下列代码写入文件<code>polls/templates/polls/index.html</code>:</p>
<div class="codehilite"><pre><span></span>{% if latest_question_list %}
    <span class="p">&lt;</span><span class="nt">ul</span><span class="p">&gt;</span>
    {% for question in latest_question_list %}
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;&lt;</span><span class="nt">a</span> <span class="na">href</span><span class="o">=</span><span class="s">&quot;/polls/{{ question.id }}/&quot;</span><span class="p">&gt;</span>{{ question.question_text }}<span class="p">&lt;/</span><span class="nt">a</span><span class="p">&gt;&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
    {% endfor %}
    <span class="p">&lt;/</span><span class="nt">ul</span><span class="p">&gt;</span>
{% else %}
    <span class="p">&lt;</span><span class="nt">p</span><span class="p">&gt;</span>No polls are available.<span class="p">&lt;/</span><span class="nt">p</span><span class="p">&gt;</span>
{% endif %}
</pre></div>


<p>同时，修改视图文件<code>polls/views.py</code>，让新的<code>index.html</code>文件生效：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span>
<span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">loader</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Question</span>

<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">latest_question_list</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;-pub_date&#39;</span><span class="p">)[:</span><span class="mi">5</span><span class="p">]</span>
    <span class="n">template</span> <span class="o">=</span> <span class="n">loader</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="s1">&#39;polls/index.html&#39;</span><span class="p">)</span>
    <span class="n">context</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;latest_question_list&#39;</span><span class="p">:</span> <span class="n">latest_question_list</span><span class="p">,</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">context</span><span class="p">,</span> <span class="n">request</span><span class="p">))</span>
</pre></div>


<p>上面的代码会加载<code>polls/index.html</code>文件，并传递给它一个参数。这个参数是一个字典，包含了模板变量名和Python对象之间的映射关系。</p>
<p>在浏览器中通过访问<code>/polls/</code>，你可以看到一个列表，包含<code>“What’s up”</code>的问卷，以及连接到其对应详细内容页面的链接点。</p>
<p>如果你显示的是<code>No polls are available.</code>说明你前面没有添加Questions对象。没关系，我们手动添加一下就可以。</p>
<p>进入admin界面，选择Questions，点击右上角的<code>Add question</code>，如下操作。</p>
<p><img alt="image.png-31.9kB" src="http://static.zybuluo.com/feixuelove1009/ce3qc91krfx5jj95334np0st/image.png" /></p>
<p>添加完后，刷新<code>/polls/</code>页面。</p>
<p><strong>快捷方式：render()</strong></p>
<p>在实际运用中，加载模板、传递参数，返回HttpResponse对象是一整套再常用不过的操作了，为了节省力气，Django提供了一个快捷方式：render函数，一步到位！看如下代码：</p>
<p>polls/views.py</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Question</span>
<span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">latest_question_list</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;-pub_date&#39;</span><span class="p">)[:</span><span class="mi">5</span><span class="p">]</span>
    <span class="n">context</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;latest_question_list&#39;</span><span class="p">:</span> <span class="n">latest_question_list</span><span class="p">}</span>
    <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;polls/index.html&#39;</span><span class="p">,</span> <span class="n">context</span><span class="p">)</span>
</pre></div>


<p>render()函数的第一个位置参数是请求对象（就是view函数的第一个参数），第二个位置参数是模板。还可以有一个可选的第三参数，一个字典，包含需要传递给模板的数据。最后render函数返回一个经过字典数据渲染过的模板封装而成的HttpResponse对象。</p>
<h2 id="404">四、返回404错误</h2>
<p>现在让我们来编写返回具体问卷文本内容的视图<code>polls/views.py</code>：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">Http404</span>
<span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Question</span>
<span class="c1"># ...</span>
<span class="k">def</span> <span class="nf">detail</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">question</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">question_id</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">Question</span><span class="o">.</span><span class="n">DoesNotExist</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">Http404</span><span class="p">(</span><span class="s2">&quot;Question does not exist&quot;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;polls/detail.html&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;question&#39;</span><span class="p">:</span> <span class="n">question</span><span class="p">})</span>
</pre></div>


<p>这里有个新知识点，如果请求的问卷ID不存在，那么会弹出一个Http404错误。</p>
<p>新建<code>polls/detail.html</code>文件，暂时写入下面的代码：</p>
<div class="codehilite"><pre><span></span>{{ question }}
</pre></div>


<p><strong>快捷方式：get_object_or_404()</strong></p>
<p>就像render函数一样，Django同样为你提供了一个偷懒的方式，替代上面的多行代码，那就是<code>get_object_or_404()</code>方法，参考下面的代码：</p>
<p>polls/views.py</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">get_object_or_404</span><span class="p">,</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Question</span>
<span class="c1"># ...</span>
<span class="k">def</span> <span class="nf">detail</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">question_id</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">get_object_or_404</span><span class="p">(</span><span class="n">Question</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="n">question_id</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;polls/detail.html&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;question&#39;</span><span class="p">:</span> <span class="n">question</span><span class="p">})</span>
</pre></div>


<p>别说我没提醒你，和render一样，也需要从Django内置的快捷方式模块中导出<code>get_object_or_404()</code>！</p>
<p><code>get_object_or_404()</code>方法将一个Django模型作为第一个位置参数，后面可以跟上任意个数的关键字参数，如果对象不存在则弹出Http404错误。</p>
<p>同样，还有一个<code>get_list_or_404()</code>方法，和上面的<code>get_object_or_404()</code>类似，只不过是用来替代<code>filter()</code>函数，当查询列表为空时弹出404错误。（filter是模型API中用来过滤查询结果的函数，它的结果是一个列表集。而get则是查询一个结果的方法，和filter是一个和多个的区别！）</p>
<h2 id="_4">五、 使用模板系统</h2>
<p><code>detail()</code>视图会将上下文变量question传递给对应的<code>polls/templates/polls/detail.html</code>模板，修改该模板的内容，如下所示：</p>
<div class="codehilite"><pre><span></span><span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>{{ question.question_text }}<span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="nt">ul</span><span class="p">&gt;</span>
{% for choice in question.choice_set.all %}
    <span class="p">&lt;</span><span class="nt">li</span><span class="p">&gt;</span>{{ choice.choice_text }}<span class="p">&lt;/</span><span class="nt">li</span><span class="p">&gt;</span>
{% endfor %}
<span class="p">&lt;/</span><span class="nt">ul</span><span class="p">&gt;</span>
</pre></div>


<p>在模板系统中圆点<code>.</code>是万能的魔法师，你可以用它访问对象的属性。在例子<code>{{ question.question_text }}</code>中，DJango首先会在question对象中尝试查找一个字典，如果失败，则尝试查找属性，如果再失败，则尝试作为列表的索引进行查询。</p>
<p>在 <code>{% for %}</code>循环中的方法调用——<code>poll.choice_set.all</code>其实就是Python的代码<code>poll.choice_set.all()</code>,它将返回一组可迭代的<code>Choice</code>对象，并用在<code>{% for %}</code>标签中。</p>
<p>这里我们对Django模板语言有个简单的印象就好，更深入的介绍放在后面。</p>
<h2 id="urls">六、删除模板中硬编码的URLs</h2>
<p>在<code>polls/index.html</code>文件中，还有一部分硬编码存在，也就是href里的“/polls/”部分：</p>
<div class="codehilite"><pre><span></span><span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">&quot;/polls/</span><span class="cp">{{</span> <span class="nv">question.id</span> <span class="cp">}}</span><span class="s">/&quot;</span><span class="nt">&gt;</span><span class="cp">{{</span> <span class="nv">question.question_text</span> <span class="cp">}}</span><span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
</pre></div>


<p>它对于代码修改非常不利。设想如果你在urls.py文件里修改了正则表达式，那么你所有的模板中对这个url的引用都需要修改，这是无法接受的！</p>
<p>我们前面给urls定义了一个name别名，可以用它来解决这个问题。具体代码如下：</p>
<div class="codehilite"><pre><span></span><span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">&quot;</span><span class="cp">{%</span> <span class="k">url</span> <span class="s1">&#39;detail&#39;</span> <span class="nv">question.id</span> <span class="cp">%}</span><span class="s">&quot;</span><span class="nt">&gt;</span><span class="cp">{{</span> <span class="nv">question.question_text</span> <span class="cp">}}</span><span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
</pre></div>


<p>Django会在<code>polls.urls</code>文件中查找<code>name='detail'</code>的url，具体的就是下面这行：</p>
<div class="codehilite"><pre><span></span>url(r&#39;^(?P&lt;question_id&gt;[0-9]+)/$&#39;, views.detail, name=&#39;detail&#39;),
</pre></div>


<p>举个栗子，如果你想将polls的detail视图的URL更换为<code>polls/specifics/12/</code>，那么你不需要在模板中重新修改url地址了，仅仅只需要在<code>polls/urls.py</code>文件中，将对应的正则表达式改成下面这样的就行了，所有模板中对它的引用都会自动修改成新的链接：</p>
<div class="codehilite"><pre><span></span># 添加新的单词&#39;specifics&#39;
url(r&#39;^specifics/(?P&lt;question_id&gt;[0-9]+)/$&#39;, views.detail, name=&#39;detail&#39;),
</pre></div>


<h2 id="url-names">七、URL names的命名空间</h2>
<p>本教程例子中，只有一个app也就是polls，但是在现实中很显然会有5个、10个、更多的app同时存在一个项目中。Django是如何区分这些app之间的URL name呢？</p>
<p>答案是使用URLconf的命名空间。在polls/urls.py文件的开头部分，添加一个<code>app_name</code>的变量来指定该应用的命名空间：</p>
<div class="codehilite"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">views</span>

<span class="n">app_name</span> <span class="o">=</span> <span class="s1">&#39;polls&#39;</span>  <span class="c1"># 关键是这行</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">index</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;index&#39;</span><span class="p">),</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;question_id&gt;[0-9]+)/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">detail</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;detail&#39;</span><span class="p">),</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;question_id&gt;[0-9]+)/results/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">results</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;results&#39;</span><span class="p">),</span>
    <span class="n">url</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;^(?P&lt;question_id&gt;[0-9]+)/vote/$&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">vote</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;vote&#39;</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>


<p>现在，让我们将代码修改得更严谨一点，将<code>polls/templates/polls/index.html</code>中的</p>
<div class="codehilite"><pre><span></span><span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">&quot;</span><span class="cp">{%</span> <span class="k">url</span> <span class="s1">&#39;detail&#39;</span> <span class="nv">question.id</span> <span class="cp">%}</span><span class="s">&quot;</span><span class="nt">&gt;</span><span class="cp">{{</span> <span class="nv">question.question_text</span> <span class="cp">}}</span><span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
</pre></div>


<p>修改为：</p>
<div class="codehilite"><pre><span></span><span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">&quot;</span><span class="cp">{%</span> <span class="k">url</span> <span class="s1">&#39;polls:detail&#39;</span> <span class="nv">question.id</span> <span class="cp">%}</span><span class="s">&quot;</span><span class="nt">&gt;</span><span class="cp">{{</span> <span class="nv">question.question_text</span> <span class="cp">}}</span><span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
</pre></div>


<p><strong>注意引用方法是冒号而不是圆点也不是斜杠！！！！！！！！！！！！</strong></p>
            </div>
            <!-- 教程正文主体部分结束 -->

            <hr />


            <!-- 打赏部分开始 -->

















            <!-- 打赏部分结束 -->


            <!-- 教程导航条 -->
            <div class="row">
                
                    <a class="pull-left" href="88.html">
                        <i class="glyphicon glyphicon-chevron-left"></i>Part 2：模型与管理后台</a>
                

                
                    <a class="pull-right" href="90.html">
                        Part 4：表单和类视图<i class="glyphicon glyphicon-chevron-right"></i></a>
                
            </div>
            <!-- 教程导航条结束 -->


            <hr />

            <!-- 评论区-->
            

            <!-- 显示评论条数-->
            <div class="row">
                
                <h3>评论总数：  15</h3>
                <hr />
            </div>

            <!-- 评论表单区-->
            <div class="row">
                
                
                <a href="89.html">登录后方可评论</a>
                
            </div>
            <!-- 评论表单区结束-->

            <hr />

            <!-- 评论显示区-->
            <div class="row">
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva3.sinaimg.cn/crop.0.0.180.180.50/90f05399jw1e8qgp5bmzyj2050050aa8.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >刘老师，本人在“模板命名空间”那里稍微有点困惑。不知道能否请教一下？？</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    手动阀暗示法
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年3月30日 21:52</em>
                                        <a href="/reply/351">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>上面原文这样说的：
“模板命名空间：
你也许会想，为什么不把模板文件直接放在polls/templates目录下，而是费劲的再建个子目录polls呢?设想这么个情况，有另外一个app，它也有一个名叫index.html的文件，当Django在搜索模板时，有可能就找到它，然后退出搜索，这就命中了错误的目标，不是我们想要的结果。解决这个问题的最好办法就是在templates目录下再建立一个与app同名的子目录，将自己所属的模板都放到里面，从而达到独立命名空间的作用，不会再出现引用错误。”

我感觉这里有点不合理。
假如有两个 app 分别叫 app_a 和 app_b，为什么 Django 搜索 app_a 的模板文件时，会跑到 app_b 的模板目录里面搜索呢？
另外，你上面又说解决这个问题的方法是在 polls 的 templates 再建立一个 polls 的子目录（为了区分其他 app），难道说其他 app 里面的模板文件也要放在 polls 的 templates 目录吗？

希望老师能指点迷津，不胜感激！！！</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >这种做法是Django的内在机制和设计理念之一</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    手动阀暗示法
                                                
                                            </span>
                                        
                                        <em>2018年3月31日 10:15</em>
                                        <a href="/reply/355">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>要这么理解：
1. 你可能有很多个app，其中甚至有不少app是别人写的，你拿来用而已
2. app的排序不一定是你希望的那个，Django只会按照既定的规则顺序查找每个app
3. Django查找模版的时候，会去每个app的templates目录下查找，这是核心机制！是每个！而不是只查找自己的html文件目录！
4.如果有多个app同时有index.html模板，那么Django找到的第一个index会被调用，而这往往不是你想要的。比如app_a排在app_b前面，那么app_a没问题了，但app_b会使用app_a中的index.html文件。
5. 为了解决这个问题，在每个app的templates目录下再创建一级目录，就相当于增加了模版命名空间限制。

多看几遍吧，能理解最好，不行就先往后放放</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 8em">
                        <div>
                            <img src="http://tva3.sinaimg.cn/crop.0.0.180.180.50/90f05399jw1e8qgp5bmzyj2050050aa8.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >感谢！！！</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    手动阀暗示法
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                            </span>
                                        
                                        <em>2018年3月31日 10:55</em>
                                        <a href="/reply/356">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>非常感谢老师的耐心教导！！！茅塞顿开！！！谢谢！！！</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva3.sinaimg.cn/crop.0.0.180.180.50/70574574jw1e8qgp5bmzyj2050050aa8.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >老师，part3第二章，访问/polls/34/报错404</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    湛蓝的微风
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2018年1月25日 18:22</em>
                                        <a href="/reply/158">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>已经按照教程检查了代码，没有错误。找了找网上的相关问答，似乎是二级路由没有生效？请问是什么原因呢？这里没办法贴图片，拜托老师解答下！</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tva3.sinaimg.cn/crop.0.0.180.180.50/70574574jw1e8qgp5bmzyj2050050aa8.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >问题补充：我的环境配置</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    湛蓝的微风
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    湛蓝的微风
                                                
                                            </span>
                                        
                                        <em>2018年1月25日 19:27</em>
                                        <a href="/reply/159">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>我是在Windows7下，用的pycharm编译器，Django版本是2.0.1，Python版本是3.6.2。麻烦老师看一下是否是这个版本下内容有差异呢？谢谢</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 8em">
                        <div>
                            <img src="http://tva3.sinaimg.cn/crop.0.0.180.180.50/70574574jw1e8qgp5bmzyj2050050aa8.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >贴一下报错内容</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    湛蓝的微风
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    湛蓝的微风
                                                
                                            </span>
                                        
                                        <em>2018年1月25日 19:30</em>
                                        <a href="/reply/160">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>这是后台页面显示的报错内容，请老师过目：
Page not found (404)
Request Method:	GET
Request URL:	http://127.0.0.1:8000/admin/polls/43/
Using the URLconf defined in perfectCRM.urls, Django tried these URL patterns, in this order:

admin/ [name=&#39;index&#39;]
admin/ login/ [name=&#39;login&#39;]
admin/ logout/ [name=&#39;logout&#39;]
admin/ password_change/ [name=&#39;password_change&#39;]
admin/ password_change/done/ [name=&#39;password_change_done&#39;]
admin/ jsi18n/ [name=&#39;jsi18n&#39;]
admin/ r/&lt;int:content_type_id&gt;/&lt;path:object_id&gt;/ [name=&#39;view_on_site&#39;]
admin/ auth/group/
admin/ auth/user/
admin/ polls/question/
admin/ ^(?P&lt;app_label&gt;auth|polls)/$ [name=&#39;app_list&#39;]
^polls/
The current path, admin/polls/43/, didn&#39;t match any of these.

You&#39;re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

在polls/后的正则都匹配不到，不知何故</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 12em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >本教程使用的是Django1.11版本</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    湛蓝的微风
                                                
                                            </span>
                                        
                                        <em>2018年1月25日 21:30</em>
                                        <a href="/reply/161">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>Django2.0在url的配置上和1.11差别较大。
建议你，pip uninstall django,然后pip install django==1.11.7</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 16em">
                        <div>
                            <img src="http://tva3.sinaimg.cn/crop.0.0.180.180.50/70574574jw1e8qgp5bmzyj2050050aa8.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >谢谢老师解答！</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    湛蓝的微风
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                            </span>
                                        
                                        <em>2018年1月25日 21:31</em>
                                        <a href="/reply/162">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>好的，谢谢！我去修改下</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 16em">
                        <div>
                            <img src="http://tva2.sinaimg.cn/crop.0.0.480.480.50/d44de8e1jw8ege96enw2qj20dc0dcaac.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >和楼上相同的问题</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    黎之殇矣
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                            </span>
                                        
                                        <em>2018年2月12日 18:00</em>
                                        <a href="/reply/214">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>一样的问题，一样的报错，并且我看您的建议，也改成了1.11.7版本的Django了，但还是不行</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 12em">
                        <div>
                            <img src="http://tva2.sinaimg.cn/crop.0.0.480.480.50/d44de8e1jw8ege96enw2qj20dc0dcaac.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >你搞定了吗？</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    黎之殇矣
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    湛蓝的微风
                                                
                                            </span>
                                        
                                        <em>2018年2月13日 11:25</em>
                                        <a href="/reply/215">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>我也是这个错误，但是我还没有搞定，想问问你怎么弄的？</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva1.sinaimg.cn/crop.426.66.1066.1066.50/0066dngsjw8f3x7oviug2j31hc0xcnb9.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >老师，part3第二章，访问/polls/34/不行啊，只能访问/34/</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    神本贪婪
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2017年12月28日 16:01</em>
                                        <a href="/reply/103">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>是需要有什么特殊的设置吗，比如r&#39;^(?P&lt;question_id&gt;[0-9]+)/$&#39;前面加个polls</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >要按照教程的步骤来</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    神本贪婪
                                                
                                            </span>
                                        
                                        <em>2017年12月28日 19:12</em>
                                        <a href="/reply/104">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>教程里分了二级路由，你需要分别编写根路由urls.py和polls应用中的urls.py。
从头开始，再检查一下代码吧。</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva1.sinaimg.cn/crop.0.0.1002.1002.50/5d1982b8jw8fap92bs1dqj20ru0rutgd.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >教程很棒</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    三杯茶XY
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2017年12月12日 14:42</em>
                                        <a href="/reply/84">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>适合已经对django有一定了解的用户当作补充教材，完全的新手看这个系列的教程会萌币</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 0em">
                        <div>
                            <img src="http://tva1.sinaimg.cn/crop.79.114.313.313.50/a33d1690jw8eqgfhcx55fj20c80fogmy.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >本页最后严谨的URL没整明白</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>By&nbsp;&nbsp;
                                                
                                                    氷湗de心
                                                
                                            </span>&nbsp;&nbsp;&nbsp;On&nbsp;&nbsp;
                                        
                                        <em>2017年11月22日 16:56</em>
                                        <a href="/reply/52">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>&#39;polls&#39; is not a registered namespace
改成最后的polls：detail后，进入网页提示这个</p>
                        </div>
                    </div>
                
                    <div class="single_comments" style="margin-left: 4em">
                        <div>
                            <img src="http://tvax1.sinaimg.cn/crop.79.178.566.566.50/005PMdg8ly8fjzip8l3ibj30k00scgr3.jpg" alt="user_image" style="width:50px; height:50px; border-radius:50%; overflow:hidden;">
                        </div>
                        <div class="col-md-11 comment-content" style="margin-bottom: 10px;">
                                    <strong >在urls.py文件中加入下面这行！</strong>
                                    <div class="entry-meta small muted">
                                        
                                            <span>
                                                
                                                    大江东流奔腾不息<span class="label label-danger">&nbsp;博主</span>
                                                
                                                <span class="glyphicon glyphicon-share-alt"></span>

                                                
                                                    氷湗de心
                                                
                                            </span>
                                        
                                        <em>2017年11月23日 08:39</em>
                                        <a href="/reply/53">&nbsp;&nbsp;回复</a>
                                    </div>
                            <br />
                            <p>app_name = &#39;polls&#39;  # 关键是这行</p>
                        </div>
                    </div>
                
            </div>
            <!-- 评论显示区结束-->

            <!-- 评论区结束-->

        </div>
        <!-- 右侧正文栏结束 -->

      </div>
    </div>




    <div id="back-to-top" >
        <span class="glyphicon glyphicon-arrow-up"></span>
    </div>


    <footer id="footer" class="midnight-blue">
        <div class="container-fluid" style="font-size: smaller">
            <div class="row footer-1">
                <div class="col-md-2">
                    Copyright &copy; 2018.刘江的官方网站
                </div>
                <div class="col-md-3">
                    托管于<a target="_blank" href="https://www.aliyun.com/">阿里云</a>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <a target="_blank" href="http://www.miitbeian.gov.cn/">京ICP备17055098号</a>
                </div>
                <div class="col-md-2">
                    <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=11010602120033">

                        <span><img style="display: inline;margin: 0 auto;" src="/static/images/ghs.png" />京公网安备11010102002019号</span>
                    </a>
                </div>
                <div class="col-md-5">
                    <ul class="pull-right">
                        <li><a href="/blog/">返回首页</a></li>
                        <li><a href="/about/">关于博主</a></li>
                        <li><a href="#">常见问题</a></li>
                        <li><a href="/contact/" target="_blank">广告合作</a></li>
                        <li><a href="/contact/" target="_blank">联系方式</a></li>
                        <li><a href="#">使用许可</a></li>
                    </ul>
                </div>
            </div>







        </div>
    </footer><!--/#footer-->

    <script src="/static/js/jquery.js"></script>
    <script src="/static/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>


    <script>


        //为新闻添加访问量
        function count_visiting(news_id){
            var to_url = "/news/visiting/"+news_id;
            jQuery.get(to_url);
        }


        $("#donate").click(function () {
            $("#donate_page").toggleClass('hidden');
        });



        <!-- 导航条对应条目active -->
        $(document).ready(function () {

            $('.navbar-nav').find('a').each(function () {
                if (this.href == document.location.href || document.location.href.search(this.href) >= 0) {
                    $(this).parent().addClass('active'); // this.parent.className = 'active';
                }
            });

            $('table').addClass('table table-bordered table-hover');

            $('img').addClass('img-responsive');

            $('#back-to-top').click(function () {
                window.scrollTo(0,0);
            });

        });

    

        $('button.navbar-toggle').click(function () {
            $('#my-navbar').css("background","#337ab7")
        });
        
    </script>

</body>

</html>